package com.gpoint.rdp.door.SearchController.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gpoint.rdp.base.core.util.string.StringUtil;
import com.gpoint.rdp.base.core.entity.ResultMessage;
import com.gpoint.rdp.base.framework.page.PageList;
import com.gpoint.rdp.base.framework.page.PageResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gpoint.rdp.api.base.query.QueryFilter;
import com.gpoint.rdp.base.web.controller.GenericController;
import com.gpoint.rdp.base.web.json.PageJson;
import com.gpoint.rdp.base.web.util.RequestUtil;
import com.gpoint.rdp.common.DoorConfig;
import com.gpoint.rdp.door.SearchController.service.SearchControllerService;
import com.gpoint.rdp.door.area.persistence.entity.ZonePo;
import com.gpoint.rdp.door.area.service.ZoneQueryService;
import com.gpoint.rdp.door.zoneCTL.persistence.entity.DoorControllerPo;
import com.gpoint.rdp.door.zoneCTL.service.DoorControllerQueryService;
import com.gpoint.rdp.door.zoneCTL.service.DoorControllerService;

import cn.pluss.platform.util.HttpResult;
import cn.pluss.platform.util.HttpUtil;

import com.gpoint.rdp.door.SearchController.service.SearchControllerQueryService;
import com.gpoint.rdp.door.SearchController.persistence.entity.SearchControllerPo;
import com.gpoint.rdp.base.core.util.AppUtil;
import com.gpoint.rdp.base.core.util.BeanUtils;
import com.gpoint.rdp.base.core.util.JacksonUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TB_DOOR_CTL_SEARCHCONTROLLER 控制类
 *
 *<pre> 
 * 开发公司：苏州东大金点信息技术有限公司
 * 开发人员：唐红锋
 * 邮箱地址：55872655@qq.com
 * 创建时间：2019-10-17 14:27:22
 *</pre>
 */
@Controller
@RequestMapping("/rdp/SearchController/searchController/")
public class SearchControllerController extends GenericController{
	@Resource
	private SearchControllerService searchControllerService;
	@Resource
	private SearchControllerQueryService searchControllerQueryService;
	
	@Resource
	private DoorControllerService doorControllerService;
	
	@Resource
	private ZoneQueryService zoneQueryService;
	
	DoorConfig config=AppUtil.getBean(DoorConfig.class);
    String servicecode=config.getServicecode();
	
	
	@Resource
	private DoorControllerQueryService doorControllerQueryService;
	
	@Value("${door.controller.get}")
	private String getUrl;
	
	@Value("${door.controller.edit}")
	private String editUrl;
	
	
	@RequestMapping("list")
	 public ModelAndView list(HttpServletRequest request,HttpServletResponse response) throws Exception{
	  ModelAndView mv=getAutoView();
	  return mv.addObject("getUrl", getUrl);
	  
	 }

	
	/**
	 * 【TB_DOOR_CTL_SEARCHCONTROLLER】列表(分页条件查询)数据
	 *
	 * @param request
	 * @param reponse
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("listJson")
	public @ResponseBody Map listJson(HttpServletRequest request,HttpServletResponse reponse) throws Exception{
		QueryFilter queryFilter = getQuerFilter(request);
		try{
			String listData = searchControllerQueryService.query(queryFilter);			
			HttpResult result = HttpUtil.doPost(getUrl);
			String body= result.getBody();
			JSONObject job = JSON.parseObject(body);
			JSONArray js=job.getJSONArray("rows");
			List<SearchControllerPo> pos = SearchControllerPo.fromJsonArrayString(js.toJSONString());
			for(SearchControllerPo po:pos) {
				DoorControllerPo door = doorControllerQueryService.getBySn(po.getProductsn());
				if(BeanUtils.isNotEmpty(door)) {
					po.setProductname(door.getControllerno());
					po.setIsAdd("1");
				}else {
					po.setProductname("");
					po.setIsAdd("0");
				}
			}			
		    Map<String,List<SearchControllerPo>> map = new HashMap<String,List<SearchControllerPo>>(256);
		    map.put("rows", pos);
		    return map;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return null;

		}
	}
				
	/** 
	 * 保存【TB_DOOR_CTL_SEARCHCONTROLLER】信息
	 *
	 * @param request
	 * @param response
	 * @param  searchController
	 * @throws Exception
	 */
	@RequestMapping("save")
	public void save(@RequestBody NetControllers param,HttpServletRequest request,HttpServletResponse response) throws Exception{
		ResultMessage message=null;
		try {
			List<SearchControllerPo> pos = param.getDatas();
			for(SearchControllerPo po:pos) {
				DoorControllerPo orgPo = doorControllerQueryService.getBySn(po.getProductsn());
				if(BeanUtils.isEmpty(orgPo)) {	
					DoorControllerPo doorController = new DoorControllerPo();
					doorController.setControllersn(po.getProductsn());
					doorController.setControllerno(po.getProductsn());
					doorController.setIpa(po.getPcip());
					doorController.setPort(po.getPort());
					doorController.setNote(po.getNotes());
					doorController.setSubmask(po.getSubmask());
					doorController.setGateway(po.getGateway());
					doorController.setEnabled("1");
					String doorsdesc = getDefaultDoorInfo(doorController);
					doorController.setDoorsnames(doorsdesc);
					doorController.setEditflag(1);
					doorController.setServicecode(servicecode);
					ZonePo rootzone = zoneQueryService.getRootZone();
					if(BeanUtils.isNotEmpty(rootzone)) {
						String zooneId = rootzone.getId();
						doorController.setZoneid(zooneId);
					}
					
					String json = JacksonUtil.toJsonString(doorController);
					doorControllerService.save(json);
				}
			}

			message=new ResultMessage(ResultMessage.SUCCESS, "保存成功");
		} catch (Exception e) {
			message=new ResultMessage(ResultMessage.FAIL, "保存失败");
			logger.error("对TB_DOOR_CTL_SEARCHCONTROLLER操作失败，" + e.getMessage(),e);
		}
		writeResultMessage(response.getWriter(), message);
	}
	
	/** 
	 * 保存【TB_DOOR_CTL_SEARCHCONTROLLER】信息
	 *
	 * @param request
	 * @param response
	 * @param  searchController
	 * @throws Exception
	 */
	@RequestMapping("update")
	public void update(@RequestBody NetControllers param,HttpServletRequest request,HttpServletResponse response) throws Exception{
		ResultMessage message=null;
		try {
			List<SearchControllerPo> pos = param.getDatas();
			for(SearchControllerPo po:pos) {
				DoorControllerPo orgPo = doorControllerQueryService.getBySn(po.getProductsn());
				if(BeanUtils.isEmpty(orgPo)) {	
					DoorControllerPo doorController = new DoorControllerPo();
					doorController.setControllersn(po.getProductsn());
					doorController.setControllerno(po.getProductsn());
					doorController.setIpa(po.getPcip());
					doorController.setPort(po.getPort());
					doorController.setNote(po.getNotes());
					doorController.setSubmask(po.getSubmask());
					doorController.setGateway(po.getGateway());
					doorController.setEnabled("1");
					String doorsdesc = getDefaultDoorInfo(doorController);
					doorController.setDoorsnames(doorsdesc);
					doorController.setEditflag(1);
					doorController.setServicecode(servicecode);
					ZonePo rootzone = zoneQueryService.getRootZone();
					if(BeanUtils.isNotEmpty(rootzone)) {
						String zooneId = rootzone.getId();
						doorController.setZoneid(zooneId);
					}
					String json = JacksonUtil.toJsonString(doorController);
					doorControllerService.save(json);
				}else {
				orgPo.setIpa(po.getPcip());
				orgPo.setPort(po.getPort());
				orgPo.setSubmask(po.getSubmask());
				orgPo.setGateway(po.getGateway());
				orgPo.setDoorsnames("");//从网络来的控制器门信息要手动更新；设置为空数据库不更新此字段					
				doorControllerService.save(JacksonUtil.toJsonString(orgPo));					
			}
			}

			message=new ResultMessage(ResultMessage.SUCCESS, "保存成功");
		} catch (Exception e) {
			message=new ResultMessage(ResultMessage.FAIL, "保存失败");
			logger.error("对TB_DOOR_CTL_SEARCHCONTROLLER操作失败，" + e.getMessage(),e);
		}
		writeResultMessage(response.getWriter(), message);
	}
	
	
	@RequestMapping("netEdit")
	public ModelAndView netEdit(HttpServletRequest request) throws Exception{
		String productid =RequestUtil.getString(request, "productid");
		String productsn=RequestUtil.getString(request, "productsn");
		String pcip=RequestUtil.getString(request, "pcip");
		String submask=RequestUtil.getString(request, "submask");
		String gateway=RequestUtil.getString(request, "gateway");
		String port =RequestUtil.getString(request, "port");
		String mac=RequestUtil.getString(request, "mac");
		String yourip=RequestUtil.getString(request, "yourip");
		String notes=RequestUtil.getString(request, "notes");
		SearchControllerPo po = new SearchControllerPo();
		po.setProductid(productid);
		po.setProductsn(productsn);
		po.setPcip(pcip);
		po.setSubmask(submask);
		po.setGateway(gateway);
		po.setPort(port);
		po.setMac(mac);
		po.setYourip(yourip);
		po.setNotes(notes);
		ModelAndView mv = new ModelAndView("/rdp/SearchController/netControllerEdit.jsp");	
		return mv.addObject("searchController", po).addObject("editUrl", editUrl);
	}
		
	private String getDefaultDoorInfo(DoorControllerPo po) {
		//doorid1+","+name1+","+doorno1+","+pc1+","+pd1+","+pe1+";"
		String sn = po.getControllersn();
		StringBuilder sb = new StringBuilder();
		if(sn.startsWith("1")) {
			sb.append("").append(",")//门ID
			  .append(sn).append(",")//门名称
			  .append(sn).append("_1").append(",")//门编号
			  .append("3").append(",")//门控制方式
			  .append("3").append(",")//延时
			  .append("11").append(",")//们控制标记
			  .append("0");//门的区域
		}else if(sn.startsWith("2")) {
			sb.append("").append(",")//门ID
			  .append(sn).append("_1").append(",")//门名称
			  .append(sn).append("_1").append(",")//门编号
			  .append("3").append(",")//门控制方式
			  .append("3").append(",")//延时
			  .append("11").append(",")//们控制标记
			  .append("0")//门的区域
			  .append(";")//分隔符
			  .append("").append(",")//门ID
			  .append(sn).append("_2").append(",")//门名称
			  .append(sn).append("_2").append(",")//门编号
			  .append("3").append(",")//门控制方式
			  .append("3").append(",")//延时
			  .append("11").append(",")//们控制标记
			 .append("0");//门的区域
		}else if(sn.startsWith("4")) {
			sb.append("").append(",")//门ID
			  .append(sn).append("_1").append(",")//门名称
			  .append(sn).append("_1").append(",")//门编号
			  .append("3").append(",")//门控制方式
			  .append("3").append(",")//延时
			  .append("10").append(",")//们控制标记
			  .append("0")//门的区域
			  .append(";")//分隔符
			  .append("").append(",")//门ID
			  .append(sn).append("_2").append(",")//门名称
			  .append(sn).append("_2").append(",")//门编号
			  .append("3").append(",")//门控制方式
			  .append("3").append(",")//延时
			  .append("10").append(",")//们控制标记
			  .append("0")//门的区域
			  .append(";")//分隔符
			  .append("").append(",")//门ID
			  .append(sn).append("_3").append(",")//门名称
			  .append(sn).append("_3").append(",")//门编号
			  .append("3").append(",")//门控制方式
			  .append("3").append(",")//延时
			  .append("10").append(",")//门控制标记
			  .append("0")//门的区域
			  .append(";")//分隔符
			  .append("").append(",")//门ID
			  .append(sn).append("_4").append(",")//门名称
			  .append(sn).append("_4").append(",")//门编号
			  .append("3").append(",")//门控制方式
			  .append("3").append(",")//延时
			  .append("10").append(",")//门控制标记
			  .append("0");//门的区域
		}else {
			return "";
		}
		return sb.toString();		
	}
	

}